﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.IO.IsolatedStorage;

namespace wallstreet
{
    public partial class Control_MyStocks : PhoneApplicationPage
    {
        public event EventHandler goToMyStocksView;

        public Control_MyStocks()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            //loadInfo();

            if (IsolatedStorageSettings.ApplicationSettings.Contains("stockList_changed"))
            {
                if (IsolatedStorageSettings.ApplicationSettings["stockList_changed"].ToString() == "true")
                {
                    loadInfo();
                }
            }
        }

        public void loadInfo()
        {
            lboMyStocks.ItemsSource = null;

            List<StockInfo> stockList = new List<StockInfo>();

            if (IsolatedStorageSettings.ApplicationSettings.Contains("stockList"))
            {
                stockList = IsolatedStorageSettings.ApplicationSettings["stockList"] as List<StockInfo>;
            }
            else
            {
                stockList.Add(new StockInfo
                {
                    Symbol = "MSFT"
                });
                stockList.Add(new StockInfo
                {
                    Symbol = "sto"
                });
            }

            if (stockList.Count > 0)
            {
                string url = "http://download.finance.yahoo.com/d/quotes.csv?s=";

                foreach (StockInfo stock in stockList)
                {
                    url = url + stock.Symbol + "+";
                }

                url = url.Substring(0, url.LastIndexOf("+"));
                url = url + "&f="
                          + "s"     //Symbol
                          + "n"     //Name
                          + "l1"    //Last Trade (Price Only)
                          + "p2";   //Change in Percent

                WebClient client = new WebClient();
                client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
                client.DownloadStringAsync(new Uri(url));
                //client.DownloadStringAsync(new Uri("http://download.finance.yahoo.com/d/quotes.csv?s=YHOO+GOOG+MSFT+aapl+sto&f=sl1d1t1c1hgvbap2"));
            }
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            List<StockInfo> stockList = new List<StockInfo>();

            using (StringReader reader = new StringReader(e.Result))
            {
                string stock;
                while ((stock = reader.ReadLine()) != null)
                {
                    //  s	=	Symbol
                    //  n	=	Name
                    //  l1	=	Last Trade (Price Only)
                    //  p2	=	Change in Percent

                    stock = stock.Replace("\"", "");
                    string[] values = stock.Split(',');

                    stockList.Add(new StockInfo { Symbol = values[0], Company = values[1], LastTrade = values[2], Change_Percent = values[3] });
                }
            }

            if (IsolatedStorageSettings.ApplicationSettings.Contains("stockList"))
                IsolatedStorageSettings.ApplicationSettings["stockList"] = stockList;
            else
                IsolatedStorageSettings.ApplicationSettings.Add("stockList", stockList);

            List<StockInfo> tempList = new List<StockInfo>();
            tempList.AddRange(stockList);
            tempList.Add(new StockInfo { Company = "" });
            tempList.Add(new StockInfo { Company = "" });
            tempList.Add(new StockInfo { Company = "" });

            lboMyStocks.ItemsSource = tempList;

            if (IsolatedStorageSettings.ApplicationSettings.Contains("stockList_changed"))
                IsolatedStorageSettings.ApplicationSettings["stockList_changed"] = "false";
            else
                IsolatedStorageSettings.ApplicationSettings.Add("stockList_changed", "false");
        }

        private void lboMyStocks_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            StockInfo selectedStock = lboMyStocks.SelectedItem as StockInfo;

            if (selectedStock != null)
            {
                if (selectedStock.Company != "")
                {
                    if (IsolatedStorageSettings.ApplicationSettings.Contains("SelectedStock"))
                        IsolatedStorageSettings.ApplicationSettings["SelectedStock"] = selectedStock;
                    else
                        IsolatedStorageSettings.ApplicationSettings.Add("SelectedStock", selectedStock);

                    goToMyStocksView(null, new EventArgs());

                    lboMyStocks.SelectedIndex = -1;
                }
            }
        }
    }
}